package algo;

/**
 * @author Ajie
 * @date 8/18/24
 * @function
 */
import java.util.ArrayList;
import java.util.List;

public class PeakDetection {

    public static void main(String[] args) {
        // 假设已经有滤波后的数据
        double[] filtered_markA = {-46.0, -39.0, -41.0, -41.0, -46.0, -43.0, -41.0, -42.0, -41.0, -39.0, -46.0, -47.0, -48.0};

        // 获取波峰的索引列表
        List<Integer> peakIndices = detectPeaks(filtered_markA);

        // 输出波峰的索引
        System.out.println("Detected peak indices: " + peakIndices);
    }

    /**
     * 检测波峰的函数
     * @param signal 输入的滤波后的数据
     * @return 波峰的索引列表
     */
    public static List<Integer> detectPeaks(double[] signal) {
        List<Integer> peakIndices = new ArrayList<>();

        // 自适应阈值设置为信号平均值
        double threshold = calculateMean(signal);

        for (int i = 1; i < signal.length - 1; i++) {
            // 检查信号的一阶导数变化方向（从正变负）
            if (signal[i - 1] < signal[i] && signal[i] > signal[i + 1]) {
                // 二阶导数为负，表明是波峰
                double secondDerivative = signal[i - 1] - 2 * signal[i] + signal[i + 1];
                if (secondDerivative < 0 && signal[i] > threshold) {
                    peakIndices.add(i);
                }
            }
        }

        return peakIndices;
    }

    /**
     * 计算信号的均值
     * @param signal 输入的信号数据
     * @return 均值
     */
    public static double calculateMean(double[] signal) {
        double sum = 0;
        for (double v : signal) {
            sum += v;
        }
        return sum / signal.length;
    }
}